package com.home766.controller.admin;

import com.home766.dto.AreaDto;
import com.home766.dto.DictionaryDTO;
import com.home766.dto.ShopsDto;
import com.home766.entity.ServiceArea;
import com.home766.entity.Shops;
import com.home766.service.IDictionaryService;
import com.home766.service.ServiceAreaService;
import com.home766.service.ShopsService;
import com.home766.util.poi.excel.BrowserUtils;
import com.home766.util.poi.excel.ExcelExportUtil;
import com.home766.util.poi.excel.entity.vo.ExcelTitle;
import net.biz.Message;
import net.biz.Page;
import net.biz.Pageable;
import net.biz.controller.admin.BaseController;
import net.biz.entity.Area;
import net.biz.entity.Sn.Type;
import net.biz.service.AdminService;
import net.biz.service.AreaService;
import net.biz.service.RoleService;
import net.biz.service.SnService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Controller - 门店
 * 
 * @author Ricky
 * @version 1.0
 */
@Controller("shopsController")
@RequestMapping("/admin/shops")

public class ShopsController extends BaseController {
	
	@Resource(name = "shopsServiceImpl")
	private ShopsService shopsService;
	@Resource(name="areaServiceImpl")
	private AreaService areaService;
	@Resource(name="snServiceImpl")
	private SnService snService;
	@Resource(name="serviceAreaServiceImpl")
	private ServiceAreaService serviceAreaService;
	@Resource(name="adminServiceImpl")
	private AdminService adminService;
	@Resource(name="dictionaryServiceImpl")
	private IDictionaryService iDictionaryService;
	
	@Resource(name = "roleServiceImpl")
	private RoleService roleService;
	
	@Value("${default_password}")
	private String DEFAULT_PASSWORD;
	@Value("${default_role_name}")
	private String DEFAULT_ROLE_NAME;
	/***
	 * 列表
	 * @param shops
	 * @param pageable
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Shops shops, Pageable pageable, ModelMap model, String properties, String sort){
		Page<Shops> page = shopsService.getShopsList(shops,pageable,properties);
		/*填充页面三级联动*/
		List<Area> parentList = areaService.findRoots();
		List<AreaDto> getChildrenListOne = areaService.findChildren(shops.getProvinceId());
		List<AreaDto> getChildrenListTwo = areaService.findChildren(shops.getCityId());
		model.addAttribute("parentList",parentList);
		model.addAttribute("getChildrenListOne",getChildrenListOne);
		model.addAttribute("getChildrenListTwo",getChildrenListTwo);
		model.addAttribute("page",page);
		model.addAttribute("shops",shops);
		model.addAttribute("sort",sort);
		return "/admin/shops/list";
	}
	/**
	 * 添加页面跳转
	 */
	@RequestMapping(value = "/addPage", method = RequestMethod.GET)
	public String addPage(ModelMap model) {
		List<Area> parentList = areaService.findRoots();
		List<DictionaryDTO> shopsTypeList = iDictionaryService.searchChildren(39L);
		List<DictionaryDTO> taxpayerType = iDictionaryService.searchChildren(44L);
		List<DictionaryDTO> storeScale = iDictionaryService.searchChildren(49L);
		List<DictionaryDTO> shopsLV = iDictionaryService.searchChildren(171L);
		Shops totalShops = shopsService.getServiceTotalShops();
		model.addAttribute("shopsTypeList",shopsTypeList);
		model.addAttribute("taxpayerType",taxpayerType);
		model.addAttribute("storeScale",storeScale);
		model.addAttribute("parentList",parentList);
		model.addAttribute("totalShops",totalShops);
		model.addAttribute("shopsLV",shopsLV);
		return "/admin/shops/add";
	}
	/***
	 * 根据省/市查询下级
	 * @param provinceId
	 * @return
	 */
	@RequestMapping(value = "/getChildrenByParentId")
	@ResponseBody
	public List<AreaDto> getChildrenByParentId(Long provinceId){
		List<AreaDto> getChildrenList = areaService.findChildren(provinceId);
		return getChildrenList;
	}
	/***
	 * 保存
	 * @param shops
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Shops shops, Long shopsLevelA, Long saAreaId, Long tempId[], Long orderShops, Long serviceShops, RedirectAttributes redirectAttributes){
		if(orderShops!=null && serviceShops!=null){
			shops.setShopsNature(2L);
		}else if(orderShops==null && serviceShops!=null){
			shops.setShopsNature(1L);
		}else if(orderShops!=null && serviceShops==null){
			shops.setShopsNature(0L);
		}
		if(shopsLevelA!=null){
			shops.setShopsA(shopsLevelA);
		}
		shops.setDeleteState(0);
		shops.setShopsCode(snService.generate(Type.shops));
		shopsService.saveShops(shops,DEFAULT_ROLE_NAME,DEFAULT_PASSWORD);
		if(saAreaId!=null){
			if(tempId!=null){
				for(int i=0;i<tempId.length;i++){
					ServiceArea serviceArea = new ServiceArea();
					serviceArea.setAreaId(tempId[i]);
					serviceArea.setShopsCode(shops.getShopsCode());
					serviceAreaService.save(serviceArea);
				}
			}
		}else{
			if(tempId!=null){
				for(int i=0;i<tempId.length;i++){
					ServiceArea serviceArea = new ServiceArea();
					serviceArea.setAreaId(tempId[i]);
					serviceArea.setShopsCode(shops.getShopsCode());
					serviceAreaService.save(serviceArea);
				}
			}
		}
		addFlashMessage(redirectAttributes,new Message(Message.Type.success,"新增成功"));
		return "redirect:list.jhtml";
	}
	/***
	 * 编辑页面跳转
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/updatePage")
	public String updatePage(Long id, ModelMap model){
		Shops shops = shopsService.find(id);
		List<ServiceArea> serviceAreaList = serviceAreaService.getListByShopsCode(shops.getShopsCode());
		/*填充页面三级联动*/
		List<Area> parentList = areaService.findRoots();
		List<AreaDto> getChildrenListOne = areaService.findChildren(shops.getProvinceId());
		List<AreaDto> getChildrenListTwo = areaService.findChildren(shops.getCityId());
		
		List<DictionaryDTO> shopsTypeList = iDictionaryService.searchChildren(39L);
		List<DictionaryDTO> taxpayerType = iDictionaryService.searchChildren(44L);
		List<DictionaryDTO> storeScale = iDictionaryService.searchChildren(49L);
		
		Shops totalShops = shopsService.getServiceTotalShops();
		
		List<DictionaryDTO> shopsLV = iDictionaryService.searchChildren(171L);
		List<Shops> shopsLevelA = shopsService.getShopsLevel(shops.getProvinceId());
		model.addAttribute("shopsTypeList",shopsTypeList);
		model.addAttribute("taxpayerType",taxpayerType);
		model.addAttribute("storeScale",storeScale);
		
		model.addAttribute("shops",shops);
		model.addAttribute("parentList",parentList);
		model.addAttribute("getChildrenListOne",getChildrenListOne);
		model.addAttribute("getChildrenListTwo",getChildrenListTwo);
		model.addAttribute("serviceAreaList",serviceAreaList);
		
		model.addAttribute("totalShops",totalShops);
		
		model.addAttribute("shopsLV",shopsLV);
		model.addAttribute("shopsLevelA",shopsLevelA);
		return "/admin/shops/edit";
	}
	/***
	 * 修改门店信息
	 * @param shops
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping("/update")
	public String update(Shops shops, Long shopsLevelA, Long saAreaId, Long tempId[], Long orderShops, Long serviceShops, RedirectAttributes redirectAttributes){
		if(orderShops!=null && serviceShops!=null){
			shops.setShopsNature(2L);
		}else if(orderShops==null && serviceShops!=null){
			shops.setShopsNature(1L);
		}else if(orderShops!=null && serviceShops==null){
			shops.setShopsNature(0L);
			tempId=null;
		}
		if(shopsLevelA!=null){
			shops.setShopsA(shopsLevelA);
		}
		shopsService.updateShops(shops);
		Shops tempShop = shopsService.find(shops.getId());
		serviceAreaService.deleteByCode(tempShop.getShopsCode());
		if(saAreaId!=null){
			if(tempId!=null){
				for(int i=0;i<tempId.length;i++){
					ServiceArea serviceArea = new ServiceArea();
					serviceArea.setAreaId(tempId[i]);
					serviceArea.setShopsCode(tempShop.getShopsCode());
					serviceAreaService.save(serviceArea);
				}
			}
		}else{
			if(tempId!=null){
				for(int i=0;i<tempId.length;i++){
					ServiceArea serviceArea = new ServiceArea();
					serviceArea.setAreaId(tempId[i]);
					serviceArea.setShopsCode(tempShop.getShopsCode());
					serviceAreaService.save(serviceArea);
				}
			}
		}
		addFlashMessage(redirectAttributes,new Message(Message.Type.success,"修改成功"));
		return "redirect:list.jhtml";
	}
	/***
	 * 查看
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/view")
	public String view(Long id, ModelMap model){
		Shops shops = shopsService.find(id);
		List<ServiceArea> serviceAreaList = serviceAreaService.getListByShopsCode(shops.getShopsCode());
		/*填充页面三级联动*/
		List<Area> parentList = areaService.findRoots();
		List<AreaDto> getChildrenListOne = areaService.findChildren(shops.getProvinceId());
		List<AreaDto> getChildrenListTwo = areaService.findChildren(shops.getCityId());
		List<DictionaryDTO> shopsTypeList = iDictionaryService.searchChildren(39L);
		List<DictionaryDTO> taxpayerType = iDictionaryService.searchChildren(44L);
		List<DictionaryDTO> storeScale = iDictionaryService.searchChildren(49L);
		List<DictionaryDTO> shopsLV = iDictionaryService.searchChildren(171L);
		List<Shops> shopsLevelA = shopsService.getShopsLevel(shops.getProvinceId());
		model.addAttribute("shops",shops);
		model.addAttribute("parentList",parentList);
		model.addAttribute("getChildrenListOne",getChildrenListOne);
		model.addAttribute("getChildrenListTwo",getChildrenListTwo);
		model.addAttribute("serviceAreaList",serviceAreaList);
		model.addAttribute("shopsTypeList",shopsTypeList);
		model.addAttribute("taxpayerType",taxpayerType);
		model.addAttribute("storeScale",storeScale);
		model.addAttribute("shopsLV",shopsLV);
		model.addAttribute("shopsLevelA",shopsLevelA);
		return "/admin/shops/view";
	}
	@RequestMapping("/delete")
	public String delete(Long[] id, RedirectAttributes redirectAttributes){
		for(Long i : id){
			try {
				Shops s = shopsService.find(i);
				s.setDeleteState(1);
				shopsService.update(s);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				addFlashMessage(redirectAttributes,new Message(Message.Type.error,"删除失败"));
			}
			addFlashMessage(redirectAttributes,new Message(Message.Type.success,"删除成功"));
		}
		return "redirect:list.jhtml";
	}
	@RequestMapping("/exportXlsShopsInfo")
	public void exportXlsShopsInfo(Shops shops,HttpServletRequest request,HttpServletResponse response){
		response.setContentType("application/vnd.ms-excel");
		String codedFileName = null;
		OutputStream fOut = null;
		List<ShopsDto> exporList=shopsService.getShopsList(shops);
		try {
			codedFileName = "导出门店信息";
			// 根据浏览器进行转码，使其支持中文文件名
			if (BrowserUtils.isIE(request)) {
				response.setHeader(
						"content-disposition",
						"attachment;filename="
								+ java.net.URLEncoder.encode(codedFileName,
										"UTF-8") + ".xls");
			} else {
				String newtitle = new String(codedFileName.getBytes("UTF-8"),
						"ISO8859-1");
				response.setHeader("content-disposition",
						"attachment;filename=" + newtitle + ".xls");
			}
			// 产生工作簿对象
			HSSFWorkbook workbook = null;
			workbook = ExcelExportUtil.exportExcel(new ExcelTitle("导出门店信息", "导出人:"+adminService.getCurrentUsername(),
					"导出信息"), ShopsDto.class, exporList);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	/***
	 * 根据省ID查询A级门店
	 * @param provinceId
	 * @return
	 */
	@RequestMapping("/getShopsAList")
	@ResponseBody
	public List<Shops> getShopsAList(Long provinceId){
		List<Shops> list = shopsService.getShopsLevel(provinceId);
		return list;
	}
}
